package org.clockwise.multimethod;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.clockwise.driver.LinkerDriver;

import Listwise.PredictLinearNeuralModel;
import Listwise.TrainLinearNeuralModel;

public class ListNet {

	public static double[] train(List<List<List<double[]>>> data) {
		List<List<double[]>> all = new ArrayList<List<double[]>>();
		Iterator<List<List<double[]>>> contextIter = data.iterator();
		while (contextIter.hasNext()) {
			List<List<double[]>> context = contextIter.next();
			Iterator<List<double[]>> queryIter = context.iterator();
			while (queryIter.hasNext()) {
				List<double[]> query = queryIter.next();
				if (query.size() == 0) {
					System.out.println("Fatal Error! Empty Query!");
				} else {
					all.add(query);
				}
			}
		}

		double[] w = TrainLinearNeuralModel.train(all);
		// for (int i = 0; i < w.length; i++) {
		// System.out.println(w[i] + ",");
		// }
		return w;
	}

	public static int test(List<List<List<double[]>>> data, double[] weight) {
		int acc = 0, all = 0;
		Iterator<List<List<double[]>>> contextIter = data.iterator();
		int contextId = 0;
		while (contextIter.hasNext()) {
			List<List<double[]>> context = contextIter.next();
			all += context.size();
			Iterator<List<double[]>> queryIter = context.iterator();
			int queryId = 0;
			while (queryIter.hasNext()) {
				List<double[]> query = queryIter.next();
				int pos = PredictLinearNeuralModel.predict(weight, query);
				if (pos == 0) {
					acc++;
				} else {
					LinkerDriver.recordError(contextId, queryId, pos, query.size(), "LNError.txt");
				}
				queryId++;
			}
			contextId++;
		}
		// System.out.println("ListNet : " + acc + "/" + all + " = " +
		// ((double)acc / all));
		return acc;
	}

}
